package com.njiandan.android;

import android.app.Application;
import android.app.Service;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.SaveCallback;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.Poi;
import com.google.gson.Gson;
import com.njiandan.android.api.LocationApi;
import com.njiandan.android.bean.BaseBean;
import com.njiandan.android.utils.RetrofitUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Administrator on 2015/9/9.
 */
public class AppContext extends Application {
    public LocationClient mLocationClient;
    public MyLocationListener mMyLocationListener;

    public TextView mLocationResult;
    public Vibrator mVibrator;

    public static String InstallationId = "";

    private LocationApi mLocationApi;
    private static double mlontitude = 0, mlatitude = 0;


    @Override
    public void onCreate() {
        super.onCreate();

        // 初始化应用信息
        AVOSCloud.initialize(this, "zSXUDIIhsOcjLdtCAn4pSnba", "N2MmmAoNOFshGqlW3ADbxiE1");

        // 启用崩溃错误统计
        AVAnalytics.enableCrashReport(this.getApplicationContext(), true);
        AVOSCloud.setLastModifyEnabled(true);
        AVOSCloud.setDebugLogEnabled(true);

        mLocationClient = new LocationClient(this.getApplicationContext());
        mMyLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);

        mLocationApi = RetrofitUtils.createApi(this, LocationApi.class, BuildConfig.API_SERVER_URL);

        AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
            public void done(AVException e) {
                if (e == null) {
                    // 保存成功
                    InstallationId = AVInstallation.getCurrentInstallation().getInstallationId();
                    // 关联  installationId 到用户表等操作……
                } else {
                    // 保存失败，输出错误信息
                }
            }
        });
    }

    public class BaseBeanCallbak implements Callback<BaseBean> {

        @Override
        public void success(BaseBean baseBean, Response response) {

        }

        @Override
        public void failure(RetrofitError error) {

        }
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
//            StringBuffer sb = new StringBuffer(256);
//            sb.append("time : ");
//            sb.append(location.getTime());
//            sb.append("\nerror code : ");
//            sb.append(location.getLocType());
//            sb.append("\nlatitude : ");
//            sb.append(location.getLatitude());
//            sb.append("\nlontitude : ");
//            sb.append(location.getLongitude());
//            sb.append("\nradius : ");
//            sb.append(location.getRadius());
//            if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
//                sb.append("\nspeed : ");
//                sb.append(location.getSpeed());// 单位：公里每小时
//                sb.append("\nsatellite : ");
//                sb.append(location.getSatelliteNumber());
//                sb.append("\nheight : ");
//                sb.append(location.getAltitude());// 单位：米
//                sb.append("\ndirection : ");
//                sb.append(location.getDirection());
//                sb.append("\naddr : ");
//                sb.append(location.getAddrStr());
//                sb.append("\ndescribe : ");
//                sb.append("gps定位成功");
//            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
//                sb.append("\naddr : ");
//                sb.append(location.getAddrStr());
//                //运营商信息
//                sb.append("\noperationers : ");
//                sb.append(location.getOperators());
//                sb.append("\ndescribe : ");
//                sb.append("网络定位成功");
//            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                sb.append("\ndescribe : ");
//                sb.append("离线定位成功，离线定位结果也是有效的");
//            } else if (location.getLocType() == BDLocation.TypeServerError) {
//                sb.append("\ndescribe : ");
//                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
//            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                sb.append("\ndescribe : ");
//                sb.append("网络不同导致定位失败，请检查网络是否通畅");
//            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                sb.append("\ndescribe : ");
//                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
//            }
//            sb.append("\nlocationdescribe : ");// 位置语义化信息
//            sb.append(location.getLocationDescribe());
//            List<Poi> list = location.getPoiList();// POI信息
//            if (list != null) {
//                sb.append("\npoilist size = : ");
//                sb.append(list.size());
//                for (Poi p : list) {
//                    sb.append("\npoi= : ");
//                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
//                }
//            }
//            sb.append("\nInstallationId:" + AppContext.InstallationId);
//            logMsg(sb.toString());
//            Log.i("BaiduLocationApiDem", sb.toString());




            double nlontitude = 0, nlatitude = 0;
            float radius = 0;
            String addr = "", locationDescribe = "", poilistStr = "";
            List<String> poilist = new ArrayList<>();
            switch (location.getLocType()) {
                case BDLocation.TypeGpsLocation:
                case BDLocation.TypeNetWorkLocation:
                case BDLocation.TypeOffLineLocation:
                    nlontitude = location.getLongitude();
                    nlatitude = location.getLatitude();
                    radius = location.getRadius();
                    addr = location.getAddrStr();
                    locationDescribe = location.getLocationDescribe(); // 位置语义化信息
                    List<Poi> listPoi = location.getPoiList();// POI信息
                    if (listPoi != null) {
                        for (Poi p : listPoi) {
                            poilist.add(p.getName());
                        }

                        poilistStr = new Gson().toJson(poilist);
                    }
                    break;
            }

            if (nlontitude != 0 && nlatitude != 0) {
                //如果两次坐标相同 不记录
                if (nlontitude == mlontitude && nlatitude == mlatitude) {
                    return;
                }
                //如果 两次坐标的距离 小于 10米 不记录
                if (mlontitude != 0 && mlatitude != 0 && distance(nlontitude, nlatitude, mlontitude, mlatitude) < 10) {
                    return;
                }

                mLocationApi.add(nlatitude, nlontitude, radius, addr, locationDescribe, poilistStr, AppContext.InstallationId, new BaseBeanCallbak());

                mlontitude = nlontitude;
                mlatitude = nlatitude;
            }
        }
    }

    /**
     * 显示请求字符串
     * @param str
     */
    public void logMsg(String str) {
        try {
            if (mLocationResult != null)
                mLocationResult.setText(str);
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }

    /**
     * 计算地球上任意两点(经纬度)距离
     *
     * @param long1 第一点经度
     * @param lat1 第一点纬度
     * @param long2 第二点经度
     * @param lat2 第二点纬度
     * @return 返回距离 单位：米
     */
    public double distance(double long1, double lat1, double long2, double lat2) {
        double a, b, R;
        R = 6378137; // 地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2
                * R
                * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1)
                * Math.cos(lat2) * sb2 * sb2));
        return d;
    }
}
